package gweb

// 系统状态

type AppState string

const (
	StateRunning  AppState = "running"  // 运行中
	StateMaintain AppState = "maintain" // 维护状态
)

func (app *GinApp) SetState(state AppState) {
	app.state = state
}

type AppStateView struct{}

func (view *AppStateView) AddRoutes(router *RouterGroup) {
	router.Config("/server", func(r *RouterGroup) {
		r.UseMiddleware(MustBeSuperuser())
		r.GET("/state", view.GetState).MaintainAllow()
		r.POST("/maintain/start", view.StartMaintain)
		r.POST("/maintain/stop", view.StopMaintain)
	})
}

func (view *AppStateView) GetState(c *Context) {
	app := c.App
	c.SuccessWithData(map[string]any{
		"state": app.state,
	})
}

func (view *AppStateView) SetState(c *Context) {
	var req struct {
		State AppState `json:"state"`
	}
	c.ShouldBindJSON(&req)
	app := c.App
	app.SetState(AppState(req.State))
	c.SuccessWithData(map[string]any{
		"state": app.state,
	})
}

func (view *AppStateView) StartMaintain(c *Context) {
	app := c.App
	app.state = StateMaintain
	c.SuccessWithData(map[string]any{
		"state": app.state,
	})
}

func (view *AppStateView) StopMaintain(c *Context) {
	app := c.App
	app.state = StateRunning
	c.SuccessWithData(map[string]any{
		"state": app.state,
	})
}

func UseAppState(router *RouterGroup) {
	router.AddViews(&AppStateView{})
}
